package com.insf.poiword.service.impl;

import com.insf.poiword.mapper.ArticleMapper;
import com.insf.poiword.pojo.Article;
import com.insf.poiword.service.ArticleService;
import com.insf.poiword.util.XwpfTUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Resource
    private ArticleMapper articleMapper;

    @Override
    public List<Article> findArticleList() {
        return articleMapper.selectArticleList();
    }

    @Override
    public void findArticleByPrimaryKey(String id, HttpServletResponse response) {
        Article article = articleMapper.selectByPrimaryKey(id);
        Map<String, Object> map = new HashMap<>();
        map.put("${title}", article.getTitile());
        map.put("${decption}", article.getDecption());
        map.put("${author}", article.getAuthor());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("${updateTime}", dateFormat.format(article.getUpdateTime()));
        map.put("${content}", article.getContent());
        export(map, response);
    }


    private void export(Map<String, Object> params, HttpServletResponse response) {
        XWPFDocument doc;
        InputStream is = null;
        OutputStream os = null;
        XwpfTUtil xwpfTUtil = new XwpfTUtil();
        try {
            //word模版的名字
            String fileNameInResource = "a.docx";
            //会在跟路径下面查看temp.doc文件。(web项目中为classes文件下面)
            is = getClass().getClassLoader().getResourceAsStream(fileNameInResource);
            if (is != null) {
                doc = new XWPFDocument(is);
                xwpfTUtil.replaceInPara(doc, params);
                //替换表格里面的变量
                xwpfTUtil.replaceInTable(doc, params);
                os = response.getOutputStream();
                response.setContentType("application/vnd.ms-excel");
                //filename为导出的word的名字
                response.setHeader("Content-disposition", "attachment;filename=" + params.get("${title}") + ".docx");
                doc.write(os);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            xwpfTUtil.close(os);
            xwpfTUtil.close(is);
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
